//
//  UniversityViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/15/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "UniversityViewController.h"

@implementation UniversityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];    
}

#pragma mark - Private Method

- (void)onSetAutocompleteDataSource:(NSArray*)aDataSource
{
    autocompleteView.dataSource = aDataSource;
    autocompleteView.keyName = @"university";
    autocompleteView.delegate = self;
}

- (void)asyncLoadUniversity
{
    if ([JGoUtility sharedUniversities] == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
        
        dispatch_async(queue, ^{
            
            NSError *error = nil;
            NSArray *universities = [JGoAPI getUniversity:&error];
            
            if (error) {
                LOG(@"%@",[error localizedDescription]);
            }
            else {
                
                [self performSelectorOnMainThread:@selector(onSetAutocompleteDataSource:) 
                                                   withObject:universities 
                                                waitUntilDone:YES];
                [JGoUtility setUniversities:universities];
            }
        });   
    }
    else {
        [self onSetAutocompleteDataSource:[JGoUtility sharedUniversities]];
    }        
}

- (void)applyAppearance
{
    [self.navigationItem setHidesBackButton:YES];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    
    [self setRightButtonImageActiveName:nil 
                          inactiveName:@"done-button" 
                                target:self 
                                action:@selector(done:)];
    
    [self setTitle:@"Create Account"];
    [self.view setAutoresizesSubviews:NO];
    autocompleteView = [[AutocompleteView alloc] initWithFrame:CGRectMake(0, 55, 320, 371)];
    [self.view addSubview:autocompleteView];
    [universityUI setText:[[JGoUtility sharedCreateAccount] objectForKey:@"university"]];    
    [universityUI becomeFirstResponder];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];     
    [self applyAppearance];
    [self asyncLoadUniversity];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [dataSource release];
    [autoDataSource release];
    
    [super dealloc];
}

#pragma mark - Action

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)done:(id)sender
{
    if ([universityUI.text length]) {
        
        [[JGoUtility sharedCreateAccount] setValue:universityUI.text forKey:@"university"];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [Utility showAlert:@"Please enter your university."];
    }        
}

#pragma mark - TextField Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    autocompleteView.hidden = NO;
    NSString *substring = [NSString stringWithString:textField.text];    
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [autocompleteView searchAutocompleteEntriesWithSubstring:substring];
    
    return YES;
}

#pragma mark - AutocompleteView Delegate

- (void)autocompleteView:(AutocompleteView *)autocompleteView didSeletedWithString:(NSString *)aString
{
    universityUI.text = aString;
}

@end
